<script setup lang="ts" name="Bet">
import API from "@/api";
import { userinfo } from "@/store";
import { showToast } from "vant";
import dayjs from "dayjs";
import router from "@/router";

const route = useRoute();
const { t } = useI18n();
const piniaUserinfo: any = userinfo();

const global: any = getCurrentInstance()?.appContext.config.globalProperties;

const data: any = reactive({
  lotteryPrice: 0, // 每注价格
  lotteryConfig: {},
  cartList: [], // 购物车
  isShowCustom: false,
  customPickList: ["-", "-", "-", "-", "-", "-", "-", "-"], // 定制票列表
  customSearchList: [], // 定制可搜索票列表
  showPicker: false,
  aboutActNames: ["1", "2"], // 关于
  isShowPayFinished: false,
  lotteryAboutList: [],
  betData:[]
});

const {
  lotteryPrice,
  lotteryConfig,
  cartList,
  isShowCustom,
  customPickList,
  customSearchList,
  showPicker,
  aboutActNames,
  isShowPayFinished,
  lotteryAboutList,
  betData
} = toRefs(data);

// header
const title = computed(() => {
  const queryData = route.query;
  return {
    text: queryData?.title,
    period: queryData?.period,
    time: queryData?.lotteryEndTime
      ? dayjs(+queryData?.lotteryEndTime).format("DD-MM-YYYY hh:ss A")
      : "",
  };
});

// 快速选择
const fastList = computed(() => {
  const num = [10, 25, 50, 100];
  return num.map((item) => {
    return {
      number: item,
      money: (lotteryPrice.value * item).toFixed(1),
    };
  });
});

// 初始化配置
const initLotteryClass = (id: string) => {
  API.getlotteryClass({
    id: +id,
  }).then((res) => {
    const data = res?.data;
    if (res?.code === 200 && data) {
      lotteryPrice.value = data?.lotteryPrice;
      lotteryConfig.value = data;
    }
  });
};
watch(
  () => route.params?.id,
  (val) => {
    if (val) {
      let tempID;
      if (typeof val !== "string") {
        tempID = val[0];
      } else {
        tempID = val;
      }
      initLotteryClass(tempID);
    }
  },
  {
    immediate: true,
  }
);

// pick可选列表
const pickList = computed(() => {
  let TempArr = []; // pick格式数据
  let singleTempArr = []; // 单个数据
  let scopeType =
    +lotteryConfig.value?.numScopeEnd - +lotteryConfig.value?.numScopeStart;
  if (lotteryConfig.value.firstLetter) {
    TempArr.push(
      lotteryConfig.value.firstLetter.split("").map((item: string) => {
        return {
          text: item,
          value: item,
        };
      })
    );
    singleTempArr.push(lotteryConfig.value.firstLetter.split(""));
  }
  if (lotteryConfig.value.randomLetter) {
    TempArr.push(
      lotteryConfig.value.randomLetter.split("").map((item: string) => {
        return {
          text: item,
          value: item,
        };
      })
    );
    singleTempArr.push(lotteryConfig.value.randomLetter.split(""));
  }
  if (scopeType) {
    let arr = [];
    let singleArr = [];
    for (let i = 0; i < lotteryConfig.value?.numScopeEnd.length; i++) {
      let min = lotteryConfig.value?.numScopeStart.split("").splice(i, 1);
      let max = lotteryConfig.value?.numScopeEnd.split("").splice(i, 1);
      let temp = [];
      let singleTemp = [];
      for (let k = +min; k <= +max; k++) {
        temp.push({
          text: k,
          value: k,
        });
        singleTemp.push(k);
      }
      arr.push(temp);
      singleArr.push(singleTemp);
    }
    TempArr.push(...arr);
    singleTempArr.push(...singleArr);
  }
  if (lotteryConfig.value.usableLetter) {
    TempArr.push(
      lotteryConfig.value.usableLetter.split("").map((item: string) => {
        return {
          text: item,
          value: item,
        };
      })
    );
    singleTempArr.push(lotteryConfig.value.usableLetter.split(""));
  }
  let partType =
    +lotteryConfig.value?.numPartEnd - +lotteryConfig.value?.numPartStart;
  if (partType) {
    let arr = [];
    let singleArr = [];
    for (let i = 0; i < lotteryConfig.value?.numPartEnd.length; i++) {
      let min = lotteryConfig.value?.numPartStart.split("").splice(i, 1);
      let max = lotteryConfig.value?.numPartEnd.split("").splice(i, 1);
      let temp = [];
      let singleTemp = [];
      for (let k = +min; k <= +max; k++) {
        temp.push({
          text: k,
          value: k,
        });
        singleTemp.push(k);
      }
      arr.push(temp);
      singleArr.push(singleTemp);
    }
    TempArr.push(...arr);
    singleTempArr.push(...singleArr);
  }
  TempArr.forEach((it) => {
    it.unshift({
      text: "-",
      value: "-",
    });
  });
  return {
    picks: TempArr,
    singlePick: singleTempArr,
  };
});

// 默认生成10个
watch(
  () => pickList.value,
  (val) => {
    console.log(pickList.value,'pickList.value.singlePick');
    const randomNumbers = generateRepeat(10, pickList.value.singlePick);
    cartList.value = randomNumbers;
    customPickList.value.length = pickList.value.picks.length;
  }
);

// 总价格
const priceAll = computed(() => {
  return (lotteryPrice.value * cartList.value.length).toFixed(1);
});

// 余额
const dealMoney = computed(() => {
  return piniaUserinfo.getUserMoney.toFixed(1);
  // return +piniaUserinfo.getUserMoney - +priceAll.value < 0
  //   ? 0
  //   : (+piniaUserinfo.getUserMoney - +priceAll.value).toFixed(1);
});

// 随机生成
const generateUniqueRandom = (arrays: any[]) => {
  let len = arrays.length;
  let result = "";
  for (let i = 0; i < len; i++) {
    const randomIndex = Math.floor(
      Math.random() * arrays[i % arrays.length].length
    );
    result += arrays[i % arrays.length][randomIndex];
  }
  return result;
};

// 重复随机
const generateRepeat = (count: number, arrays: any[]) => {
  const generatedStrings = new Set();
  while (generatedStrings.size < count) {
    const randomString = generateUniqueRandom(arrays);
    if (!generatedStrings.has(randomString)) {
      generatedStrings.add(randomString);
    }
  }
  return [...generatedStrings];
};

// 快速选择批量彩票
const handleFastItem = (item: any) => {
  console.log("handleFastItem", item, pickList.value.singlePick);
  if ((item?.number, pickList.value?.singlePick)) {
    const randomNumbers = generateRepeat(
      item.number,
      pickList.value.singlePick
    );
    cartList.value = randomNumbers;
  }
};

// 打开定制项
const handleCustom = () => {
  console.log("handleCustom");
  isShowCustom.value = true;
};

// 重置定制
const handleResetCustom = () => {
  customPickList.value = ["-", "-", "-", "-", "-", "-", "-", "-"];
  customPickList.value.length = pickList.value.picks.length;
  customSearchList.value = [];
};

// 关闭定制
const handleCustomClose = () => {
  isShowCustom.value = false;
  handleResetCustom();
};

// 打开号码选择
const handleShowPick = () => {
  showPicker.value = true;
};

const handlePickChange = () => {};

// 选择彩票号码
const handlePickSelect = ({ selectedValues }: any) => {
  let realArr = selectedValues.filter((it: any) => it !== "-");
  let needLan = customPickList.value.length - 2;

  if (realArr.length < needLan) {
    showToast({
      message: t("bet.status1").replace("*", "" + needLan),
      position: "top",
    });
    return;
  }
  customPickList.value = selectedValues;
  showPicker.value = false;
};

const combineArrays = (arrays: any[]) => {
  const result = [[]];

  for (const currentArray of arrays) {
    const newResult: any = [];
    for (const resultItem of result) {
      for (let i = 0; i < currentArray.length; i++) {
        newResult.push([...resultItem, currentArray[i]]);
      }
    }
    result.length = 0;
    result.push(...newResult);
  }

  return result;
};
// 重复随机
const generateCustomRepeat = (arrays: any[], allArray: any[]) => {
  let tempCustomArr = [];
  let indices = [];
  let comArr = [];
  for (let i = 0; i < arrays.length; i++) {
    if (arrays[i] === "-") {
      indices.push(i);
      tempCustomArr.push(allArray[i]);
    }
  }

  let resList: any[] = combineArrays(tempCustomArr);

  if (resList) {
    for (let j = 0; j < resList.length; j++) {
      let copyArr = [...arrays];
      for (let k = 0; k < indices.length; k++) {
        copyArr.splice(indices[k], 1, resList[j][k]);
      }
      comArr.push(copyArr);
    }
  }

  return comArr;
};

// 搜索定制列表
const handleSearchCustom = () => {
  console.log("handleSearchCustom", customPickList.value);
  let realArr = customPickList.value.filter((it: any) => it !== "-");
  let needLan = customPickList.value.length - 2;

  if (realArr.length < needLan) {
    showToast({
      message: t("bet.status1").replace("*", "" + needLan), //`请至少选择${needLan}位`,
      position: "top",
    });
    return;
  }

  // 计算可能得出的全部数据
  const searchList = generateCustomRepeat(
    customPickList.value,
    pickList.value.singlePick
  ).sort(() => 0.5 - Math.random());
  const resultArr = searchList.map((subArray) => subArray.join(""));

  // 过滤已经加入到购物车的的数据
  const filterData = resultArr.filter(
    (value) => !cartList.value.includes(value)
  );
  console.log("filterData", filterData);
  customSearchList.value = filterData;
};

// 选择全部搜索项到购物车
const handlePickAll = () => {
  cartList.value = [...cartList.value, ...customSearchList.value];
  customSearchList.value = [];
};

// 删除搜索列表的选择项
const handleSearchCartItemDel = (item: any, index: number) => {
  customSearchList.value.splice(index, 1);
};

// 删除购物车全部
const handleDelCart = () => {
  cartList.value = [];
};

// 删除购物车某一个
const handleCartItemDel = (item: any, index: number) => {
  console.log("item", item);
  cartList.value.splice(index, 1);
};

// 添加到购物车
const handleCartItemAdd = () => {
  const randomNumbers = generateRepeat(1, pickList.value.singlePick);
  cartList.value = cartList.value.concat(randomNumbers);
};

// 购买
const handleBuy = () => {
  if (!route.params?.id && !title.value.period) return;
  let listData = cartList.value.map((item: string) => {
    return {
      content: item,
      noteNum: 1,
    };
  });
  API.orderlotteryBet({
    lotteryPlanId: +route.params?.id,
    period: title.value.period,
    betContent: listData,
  }).then((res) => {
    if (res.code === 200) {
      piniaUserinfo.queryUserMoney();
      isShowPayFinished.value = true;
      betData.value = res.data
    }
  });
};

// 查看历史
const handleGoHistory = () => {
  let type = lotteryConfig.value.lotteryTypeCode;
  router.push(`/me/account?type=${type}`);
};

// 查询奖项结构
const initlotteryList = async () => {
  try {
    let res = await API.getlotteryList({});
    if (res?.code === 200) {
      lotteryAboutList.value = res.data || [];
    }
  } catch (error) {}
};
initlotteryList();

const levelFunc = (ruleGrade: Number) => {
  switch (ruleGrade) {
    case 1:
      return t("result.test4");
    case 2:
      return t("result.test5");
    case 3:
      return t("result.test6");
    case 4:
      return t("result.test7");
    case 5:
      return t("result.test8");
    case 6:
      return t("result.test9");
  }
};
const conditionFunc = (ruleGrade: Number) => {
  switch (ruleGrade) {
    case 1:
      return t("bet.test58");
    case 2:
      return t("bet.test64");
    case 3:
      return t("bet.test63");
    case 4:
      return t("bet.test62");
    case 5:
      return t("bet.test61");
    case 6:
      return t("bet.test60");
    case 7:
      return t("bet.test59");
    case 8:
      return t("bet.test65");
  }
};
const lotteryAboutTable = computed(() => {
  return lotteryAboutList.value.find(
    (it: any) => it?.lotteryClassId == route.params?.id
  )?.ruleList;
});
</script>

<template>
  <div class="betWrap">
    <DetailHeader :isNeedBackIcon="true">
      <template #title>
        <p class="title1">{{ title.text }} {{ title.period }}</p>
        <p class="title2">
          {{ t("bet.test1") }}：<span class="time">{{ title.time }}</span>
        </p>
      </template>
    </DetailHeader>
    <div class="content">
      <div class="fastWrap">
        <div class="fastList">
          <div
            class="fastItem"
            v-for="(item, index) in fastList"
            :key="index"
            @click="handleFastItem(item)"
          >
            <div class="fastLeft">
              <p>{{ t("bet.test2").replace("x", "" + item?.number) }}</p>
              <p>
                {{ t("bet.test4") }} <span>₹{{ item.money }}</span>
              </p>
            </div>
            <div class="fastRight">
              <Iconfont name="icon-icon_gouwuche" color="#FFF" size="20" />
            </div>
          </div>
        </div>
        <div
          class="customBtn"
          @click="handleCustom"
          v-html="t('bet.test3')"
        ></div>
      </div>

      <!-- custom -->
      <div class="customWrap" v-if="isShowCustom">
        <div class="customTop">
          <h3>{{ t("bet.test51") }}</h3>
          <Iconfont
            name="icon-icon_close"
            color="#FFF"
            size="20"
            @click="handleCustomClose"
          />
        </div>
        <!-- grid-template-columns -->
        <div
          class="customList"
          :style="{
            gridTemplateColumns: `repeat(${pickList.picks.length}, 1fr)`,
          }"
        >
          <div
            class="customItem"
            v-for="(item, index) in customPickList"
            :key="index"
            @click="handleShowPick"
          >
            <span>{{ item }}</span>
            <img src="../../assets/images/Home/icon-arrow.svg" alt="" />
          </div>
        </div>
        <div class="operation">
          <div class="searchBtn" @click="handleSearchCustom">
            {{ t("bet.test7") }}
          </div>
          <div class="reset" @click="handleResetCustom">
            {{ t("bet.test8") }}
          </div>
        </div>
        <div class="searchWrap">
          <div class="searchTop">
            <div class="searchTitle">{{ t("bet.test9") }}</div>
            <div class="searchPickAll" @click="handlePickAll">
              {{ t("bet.test10") }}
            </div>
          </div>
          <ul class="searchList">
            <li
              class="searchItem"
              v-for="(item, index) in customSearchList"
              :key="index"
            >
              <p>{{ item }}</p>
              <span @click="handleSearchCartItemDel(item, index)">-</span>
            </li>
          </ul>
        </div>
      </div>

      <!-- cart -->
      <div class="cart">
        <div class="cartTop">
          <div class="cartTitle">
            <Iconfont name="icon-icon_gouwuche" color="#FFF" size="20" />
            <span class="cartText"
              >{{ t("bet.test5") }} ({{ cartList.length }})</span
            >
          </div>
          <Iconfont
            name="icon-icon_delete"
            color="#FFF"
            size="20"
            @click="handleDelCart"
          />
        </div>
        <ul class="cartContent">
          <li class="cartItem" v-for="(item, index) in cartList" :key="index">
            <p>{{ item }}</p>
            <span @click="handleCartItemDel(item, index)">-</span>
          </li>
          <li class="lastAdd" @click="handleCartItemAdd">
            <Iconfont name="icon-icon_tianjia" color="#FFF" size="14" />
            &nbsp;{{ t("bet.test6") }}
          </li>
        </ul>
      </div>

      <!-- about -->
      <div class="about">
        <van-collapse v-model="aboutActNames">
          <van-collapse-item
            :title="t('bet.test11')"
            name="1"
            class="aboutContent"
          >
            <h3>{{ t("bet.test13") }}</h3>
            <p>
              {{ t("bet.test14") }}
            </p>
            <p>
              {{ t("bet.test15") }}
            </p>
            <br />
            <h3>{{ t("bet.test16") }}</h3>
            <p>{{ t("bet.test17") }}</p>
            <p>{{ t("bet.test18") }}</p>
          </van-collapse-item>
          <van-collapse-item
            :title="t('bet.test12')"
            name="2"
            class="aboutContent"
          >
            <template v-if="lotteryAboutTable?.length">
              <h3>{{ t("bet.test19") }}</h3>
              <table class="aboutTable" border="1">
                <thead>
                  <tr>
                    <th>{{ t("bet.test20") }}</th>
                    <th>{{ t("bet.test21") }}</th>
                    <th>{{ t("bet.test22") }}</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item, index) in lotteryAboutTable" :key="index">
                    <td>{{ levelFunc(item?.ruleGrade) }}</td>
                    <td>{{ conditionFunc(item?.ruleGrade) }}</td>
                    <td>{{ item?.ruleBonus }}</td>
                  </tr>
                </tbody>
              </table>
            </template>
            <h3>{{ t("bet.test23") }}</h3>
            <p>
              {{ t("bet.test24") }}
            </p>
            <br />
            <h3>{{ t("bet.test25") }}</h3>
            <p>
              {{ t("bet.test26") }}
              {{ t("bet.test27") }}
            </p>
            <br />
            <h3>{{ t("bet.test28") }}</h3>
            <p>
              {{ t("bet.test29") }}
            </p>
            <br />
            <h3>{{ t("bet.test30") }}</h3>
            <p>
              {{ t("bet.test31") }}
              <br />
              {{ t("bet.test32") }}
              <br />
              {{ t("bet.test33") }}
            </p>
          </van-collapse-item>
        </van-collapse>
      </div>
    </div>

    <!-- pick -->
    <van-popup v-model:show="showPicker" round position="bottom">
      <van-picker
        :columns="pickList.picks"
        @cancel="showPicker = false"
        @confirm="handlePickSelect"
        @change="handlePickChange"
        class="pickCustom"
      >
        <template #cancel></template>
        <template #title>
          <div class="pickCustomTitle">
            <h3>{{ t("bet.test52") }}</h3>
            <p>
              ({{
                t("bet.test53").replace(
                  "*",
                  "" + (pickList?.picks?.length - 2)
                )
              }})
            </p>
          </div>
        </template>
      </van-picker>
    </van-popup>

    <div class="buyComputed">
      <div class="left">
        <div class="moneyWrap">
          <span
            >{{ t("bet.test34") }} {{ cartList?.length
            }}{{ t("bet.test35") }}</span
          >
          <span>₹</span>
          <span>{{ priceAll }}</span>
        </div>
        <div class="balanceWrap">
          <span>{{ t("bet.test36") }}</span>
          <span>₹</span>
          <span>{{ dealMoney }}</span>
        </div>
      </div>
      <div class="right">
        <van-button
          :disabled="!cartList.length"
          round
          type="primary"
          @click="handleBuy"
        >
          {{ t("bet.btn1") }}
        </van-button>
      </div>
    </div>

    <van-dialog
      class="payDialog"
      v-model:show="isShowPayFinished"
      :title="t('bet.test37')"
      show-cancel-button
      :cancel-button-text="t('bet.btn2')"
      cancel-button-color="#9CA2A9"
      :confirm-button-text="t('bet.btn3')"
      confirm-button-color="#3497FB"
      @confirm="handleGoHistory"
    >

      <img src="../../assets/images/Bet/success.svg" alt="" />
      <div class="betInfo" v-if="betData.length>0">
        <p>{{  t('bet.bet17')}}</p>
        <p>{{  t('bet.bet18')}}</p>
      </div>
    </van-dialog>
  </div>
</template>

<style lang="scss" scoped>
@import url("./index.scss");
</style>
<style lang="scss">
.payDialog {
  text-align: center;
  .van-dialog__header {
    color: #ff2d55;
  }
  .van-dialog__content {
    img {
      margin: 15rem auto;
      width: 50rem;
      height: 50rem;
    }
  }
}
</style>
